﻿using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsAppVideo
{
    internal class OpenCvSharpUtils
    {
        private VideoCapture Capture;
        private VideoWriter VideoWriter;
        private PictureBox PictureBox;
        private bool StopFlag = false;
        private bool SaveFlag = false;

        //
        public void OpenVideo(string rtspUrl, PictureBox PictureBox)
        {
            Capture = new VideoCapture(rtspUrl);
            int time = Convert.ToInt32(Math.Round(1000 / Capture.Fps));
            while (!StopFlag)
            {
                if (Capture == null || Capture.IsDisposed)
                {
                    continue;
                }
                Mat mat = new Mat();
                bool res = Capture.Read(mat);//会阻塞线程
                if (!res || mat.Empty())
                {
                    continue;
                }
                if (SaveFlag && VideoWriter != null)
                {
                    VideoWriter.Write(mat);
                }
                if (PictureBox != null)
                {
                    System.Drawing.Image image = PictureBox.Image;
                    PictureBox.Image = BitmapConverter.ToBitmap(mat);
                    if (image != null)
                    {
                        image.Dispose();//释放以前的图片，不然吃内存
                    }
                }
                Cv2.WaitKey(time);

                mat.Dispose();
            }
            Capture.Dispose();
        }

        public void CloseVideo()
        {
            StopFlag = true;
        }

        public bool StartRecord(string videoFullPath)
        {
            if (Capture == null || Capture.IsDisposed)
            {
                return false;
            }
            VideoWriter = new VideoWriter(videoFullPath, FourCC.MPG4, Capture.Fps, new OpenCvSharp.Size(Capture.FrameWidth, Capture.FrameHeight));
            SaveFlag = true;
            return true;
        }

        public bool StopRecord()
        {
            SaveFlag = false;
            if (VideoWriter != null && !VideoWriter.IsDisposed)
            {
                VideoWriter.Dispose();
                VideoWriter = null;
            }
            return true;
        }
    }
}
